package command;

import parser.ChessContentHandlerConstants;
import parser.ParserConstants;

public class CastleCommand implements Command {

	private chess.Tile rookOrigTile;
	private chess.Tile rookDestTile;
	private boolean rookMovedPreviously;
	private Command secondaryCommand;
	public CastleCommand(chess.Tile orig, chess.Tile dest){
		rookOrigTile=orig;
		rookDestTile=dest;
		rookMovedPreviously=orig.getPieceHere().hasMoved();
		secondaryCommand=new NoSecondaryCommand();
	}
	
	@Override
	public void execute() {
		rookOrigTile.getPieceHere().setMoved(true);
		MoveCommand secondMove = new MoveCommand(rookOrigTile,rookDestTile);
		secondMove.execute();
		secondaryCommand.execute();

	}

	public void addSecondaryCommand(Command secondaryCommand) {
		if (this.secondaryCommand instanceof NoSecondaryCommand){
			this.secondaryCommand = secondaryCommand;
		}
		else{
			this.secondaryCommand.addSecondaryCommand(secondaryCommand);
		}

	}

	@Override
	public void undo() {
		secondaryCommand.undo();
		MoveCommand undoMove = new MoveCommand(rookDestTile,rookOrigTile);
		undoMove.execute();
		rookOrigTile.getPieceHere().setMoved(rookMovedPreviously);

	}

	public boolean hadMovedPreviously(){
		return false;
	}
	/**
	 * This method will return a string representation of the command used for importing and
	 * exporting
	 * @return Returns a string representing the object
	 */
	public String exportCode(){
		return "Castle:" + rookOrigTile.toString() + "to" + rookDestTile.toString();
	}
	/**
	 * This method will return a string representation of the command used for saving and
	 * loading
	 * @return Returns a string representing the object
	 */
	@Override
	public String xmlCode() {
		String code = "<" + ParserConstants.ELEMENT_CASTLE + ">\n";
		
		code += "\t" + rookOrigTile.XMLPointTag(ChessContentHandlerConstants.POINT_1).replaceAll("\n", "\n\t");
		code += "\n";
		code += "\t" + rookDestTile.XMLPointTag(ChessContentHandlerConstants.POINT_2).replaceAll("\n", "\n\t");
		code += "\n";
		code += "</" + ParserConstants.ELEMENT_CASTLE + ">\n";
		code += secondaryCommand.exportCode();
		return code;
	}

	@Override
	public Command getSecondaryCommand() {
		return secondaryCommand;
	}
}
